import redis
import socket
def run_diagnostics():
    print("开始Redis诊断...")
    # 1. 检查端口
    print("\n1. 检查Redis端口(6379)...")
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    try:
        sock.bind(('127.0.0.1', 6379))
        print("端口6379可用")
        port_available = True
    except socket.error:
        print("端口6379已被占用")
        port_available = False
    finally:
        sock.close()
    if not port_available:
        print("端口被占用，可能Redis服务正在运行")
    # 2. 测试连接
    print("\n2. 测试Redis连接...")
    try:
        r = redis.Redis(
        host='localhost',
        port=6379,
        db=0,
        decode_responses=True,
        socket_timeout=5
        )
        r.ping()
        print("Redis连接成功！")
        connection_ok = True
    except redis.ConnectionError as e:
        print(f"Redis连接错误: {str(e)}")
        connection_ok = False
    except Exception as e:
        print(f"发生错误: {str(e)}")
        connection_ok = False
    # 3. 测试基本操作
    if connection_ok:
        print("\n3. 测试基本操作...")
    try:
        # 设置值
        r.set('test_key', 'Hello Redis')
        print("设置键值对成功")
        # 获取值
        value = r.get('test_key')
        print(f"获取到的值: {value}")
        # 删除键
        r.delete('test_key')
        print("删除测试键成功")
        print("基本操作测试通过！")
        operations_ok = True
    except Exception as e:
        print(f"基本操作测试失败: {str(e)}")
        operations_ok = False
        # 4. 输出诊断结果
        print("\n诊断结果:")
        print(f"端口状态: {'可用' if port_available else '被占用'}")
        print(f"连接状态: {'成功' if connection_ok else '失败'}")
        if connection_ok:
            print(f"操作测试: {'成功' if operations_ok else '失败'}")
    # 5. 建议
    print("\n建议:")
    if not port_available and not connection_ok:
        print("1. Redis服务可能未正确启动")
        print("2. 请检查Redis服务是否在运行")
    elif port_available and not connection_ok:
        print("1. Redis服务未运行")
        print("2. 请启动Redis服务")
    elif connection_ok and not operations_ok:
        print("1. Redis服务运行中但操作失败")
        print("2. 请检查Redis配置")
    else:
        print("Redis运行正常，可以正常使用！")
        
if __name__ == "__main__":
    run_diagnostics()
